package com.autonavi.yunda.yunji.common.utils.http.interceptor;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * @author cizhong.wcs
 * @date 2022/1/25 11:02 上午
 */
@Slf4j
public class OkHttpRetryInterceptor implements Interceptor {

    private final int retryCount;

    public OkHttpRetryInterceptor(int retryCount) {
        this.retryCount = retryCount;
    }

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        int count = 0;
        IOException ex;
        do {
            if (count > 0) {
                log.warn("okhttp retry request , content = {}, retryTime = {} time start ...", request, count);
            }
            try {
                return chain.proceed(request);
            } catch (IOException e) {
                log.error("okhttp request error, request = {}, retryTime = {}", request, count, e);
                ex = e;
            }
            count++;
        } while (count <= retryCount);
        throw ex;
    }
}
